package com.example.filterdemo.filter;



import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class RequestTimingFilter extends OncePerRequestFilter {

    private static final String REQUEST_START_TIME = "requestStartTime";

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {

        // 记录请求开始时间
        long startTime = System.currentTimeMillis();

        // 打印请求信息
        System.out.println("Request Started: " + request.getMethod() + " " + request.getRequestURI());

        try {
            // 继续处理请求链
            filterChain.doFilter(request, response);
        } finally {
            // 计算处理耗时
            long duration = System.currentTimeMillis() - startTime;
            System.out.println("Request Completed: " + request.getMethod() + " " + request.getRequestURI() + " | Duration: " + duration + "ms");
        }
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        // 排除特定路径（如健康检查）
        return request.getRequestURI().startsWith("/actuator/health");
    }
}